package jpb.hotspot;

import jpb.*;

import static jpb.Assert.notNull;

/**
 * {@link jpb.JvmArg} implementation for Hotspot supporting the {@link jpb.EntryPoint}.
 *
 *
 * @see jpb.JvmArg
 * @see jpb.EntryPoint
 * @see jpb.Jvm#entryPointArg()
 * @author Dariusz Kordonski
 */
final class EntryPointArg extends CoreJvmArgs.AbstractEntryPointArg {

    private static final String JAR_MODE = "-jar";

    EntryPointArg() {
        super(HotspotJvm.class);
    }

    @Override
    protected void validate(EntryPoint argValue) {
        if (!DefaultEntryPoint.class.isInstance(argValue)) {
            throw new InvalidJvmArgException(this, argValue, "EntryPoint implementation not supported: " + argValue);
        }
        DefaultEntryPoint entryPoint = (DefaultEntryPoint) argValue;
        if (entryPoint.isClassEntryPoint()) {
            assertHasClass(entryPoint);
        } else if (entryPoint.isJarEntryPoint()) {
            assertHasJar(entryPoint);
        } else {
            throw new InvalidJvmArgException(this, argValue, "Not recognized entry point: " + entryPoint);
        }
    }

    private void assertHasClass(DefaultEntryPoint entryPoint) {
        notNull("entryPoint.className", entryPoint.className());
    }

    private void assertHasJar(DefaultEntryPoint entryPoint) {
        notNull("entryPoint.jarFile", entryPoint.jarFile());
    }

    @Override
    protected CommandArg convert(EntryPoint argValue) {
        notNull("argValue", argValue);
        DefaultEntryPoint entryPoint = (DefaultEntryPoint) argValue;
        if (entryPoint.isClassEntryPoint()) {
            return createClassEntryPointArg(entryPoint);
        } else if (entryPoint.isJarEntryPoint()) {
            return createJarEntryPointArg(entryPoint);
        } else {
            throw new InvalidJvmArgException(this, argValue, "Not recognized entry point: " + entryPoint);
        }
    }

    private CommandArg createClassEntryPointArg(DefaultEntryPoint entryPoint) {
        return CommandArg.of(entryPoint.className());
    }

    private CommandArg createJarEntryPointArg(DefaultEntryPoint entryPoint) {
        return CommandArg.of(JAR_MODE, entryPoint.jarFile().getAbsolutePath());
    }
}
